package com.liuzhilin.service;

import com.liuzhilin.domain.Article;
import com.liuzhilin.domain.Message;
import com.liuzhilin.domain.User;
import com.liuzhilin.mapper.DatabaseOperations;
import com.liuzhilin.mapper.DatabaseSQl;
import com.liuzhilin.mapper.JDBC;
import com.liuzhilin.util.BCryptService;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/*
* 管理员功能的方法
* */
public class ManagerService {
    // 管理员登录，密码检验
    public static boolean managerLogin(String managerName,String password){
        String realPassword =passwordSelect(managerName);
        if (realPassword == null) {
            return false;
        }
        // 密码校验
        if (BCryptService.checkPassword(password, realPassword)) {
            return true;
        } else {
            return false;
        }
    }
    // 根据管理员名查询管理员密码
    public static String passwordSelect(String managerName)
    {
        Object[] objects = {managerName};
        ResultSet resultSet = DatabaseOperations.executeQuery(DatabaseSQl.managerNameSql(), objects);
        try {
            // 判断管理员是否存在
            if (resultSet.next()) {
                return resultSet.getString("password");
            } else {
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    // 根据管理员名查询管理员id
    public static int managerIdSelect(String managerName) {
        Object[] objects = {managerName};
        ResultSet resultSet = DatabaseOperations.executeQuery(DatabaseSQl.managerNameSql(), objects);
        //查询管理员的id，id在数据库中以int的形式储存
        int id=8;
        try{
            resultSet.next();
            id=resultSet.getInt("id");
        }catch (SQLException e){
            e.printStackTrace();
        }
        return id;
    }
    // 根据管理员id查询管理员类型
    public static String managerInformationSelect(String managerName) {
        int id=managerIdSelect(managerName);
        switch (id){
            case 1:
                return "游戏区";
            case 2:
                return "科技区";
            case 3:
                return "体育区";
            case 4:
                return "军事区";
            case 5:
                return "农业区";
            case 6:
                return "艺术区";
            default:
                return "超级";
        }
    }
    // 获取所有文章
    public static List<Article> getArticles(String managerName,String type){
        String managerType = managerInformationSelect(managerName);
        //将type 转换为int类型
        int typeInt = Integer.parseInt(type);
        List<Article> articles = new ArrayList<>();
        ResultSet rS = DatabaseOperations.executeQuery(DatabaseSQl.allArticleSql(), null);
        Set<String> uniqueArticleKeys = new HashSet<>();
        try {
            while (rS.next()) {
                int status = rS.getInt("status");
                String articleKey = rS.getString("title") + "-" + rS.getString("writer") + "-" + rS.getString("publishTime");
                // 判断文章是否被审核，并且判断文章所属板块是否为该管理员所属板块
                if (status ==typeInt && managerType.equals(rS.getString("category")) && !uniqueArticleKeys.contains(articleKey)) {
                    Article article = new Article(
                            rS.getString("writer"),
                            rS.getString("title"),
                            rS.getString("content"),
                            rS.getString("publishTime"),
                            rS.getString("category"),
                            rS.getInt("status"),
                            rS.getInt("like"),
                            rS.getInt("comment"),
                            rS.getInt("favorite")
                    );
                    articles.add(article);
                    uniqueArticleKeys.add(articleKey);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return articles;
    }
    //更改文章的审核状态
    public static boolean passArticle(String writer,String title,String category){
        Object[] objects = {writer,title,category};
        // 更新文章状态为1，表示审核通过
        try {
            DatabaseOperations.executeUpdate(DatabaseSQl.passArticleSql(),objects);
        }catch (Exception e){
            return false;
        }
        //更新用户文章数量
        try {
            Object[] username = {writer};
            DatabaseOperations.executeUpdate(DatabaseSQl.updateUserArticleCountSql(),username);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
    //删除没有审核通过的文章
    public static boolean deleteArticle(String writer,String title,String category){
        Object[] objects = {writer,title,category};
        try {
            ResultSet resultSet =DatabaseOperations.executeQuery(DatabaseSQl.selectArticleStatusSql(),objects);
            // 判断文章是否存在，如果存在，则减少用户文章数量（对删除审核通过时的文章奏效）
            if (resultSet.next()){
                Object[] username = {writer};
                DatabaseOperations.executeUpdate(DatabaseSQl.updateUserArticleCountMinusSql(),username);
            }
        }catch (Exception e){
            return false;
        }
        //删除文章
        try {
            DatabaseOperations.executeUpdate(DatabaseSQl.deleteArticleSql(),objects);
        }catch (Exception e){
            return false;
        }
        return true;
    }
    // 更改文章的审核状态为不通过
    public static boolean notPassArticle(String writer,String title,String category){
        Object[] objects = {writer,title,category};
        try {
            DatabaseOperations.executeUpdate(DatabaseSQl.notPassArticleSql(),objects);
        }catch (Exception e){
            return false;
        }
        return true;
    }

    public static List<User> getUsers(String managerName){
        List<User> users = new ArrayList<>();
        ResultSet resultSet = DatabaseOperations.executeQuery(DatabaseSQl.userSql(),null);
        try {
            while (resultSet.next()){
                User user = new User(
                        resultSet.getInt("id"),
                        resultSet.getString("userName"),
                        resultSet.getString("password"),
                        resultSet.getString("personalSignature"),
                        resultSet.getInt("articleCount"),
                        resultSet.getDate("birthday"),
                        resultSet.getInt("status")
                );
                users.add(user);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return users;

    }

    public static boolean updateUserStatus(int operation,String managerName,int userId){
        int managerId = managerIdSelect(managerName);
        // 管理员id=0，则默认为超级管理员
        if (managerId==0){
            managerId=7;
        }
        //1解锁账号，2禁用账号
        if(operation==1){
            Object[] objects = {userId};
            try {
                DatabaseOperations.executeUpdate(DatabaseSQl.lockdownUserStatusSql(),objects);
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
        }else{
            Object[] objects = {managerId,userId};
            try {
                DatabaseOperations.executeUpdate(DatabaseSQl.disableUserStatusSql(),objects);
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
        }
        //根据用户id查询用户名
        try {
            Object[] objects = {userId};
            ResultSet resultSet = DatabaseOperations.executeQuery(DatabaseSQl.selectUserByIdSql(),objects);
            while (resultSet.next()){
                String userName = resultSet.getString("userName");
                if(managerName!=null){
                    if(operation==1){
                        ManagerService.recordOperationLog(managerName, "解封了用户"+userName,userName);
                    }else{
                        ManagerService.recordOperationLog(managerName, "封禁了用户"+userName,userName);
                    }

                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;

    }

    // 批量更新用户状态
    public static boolean batchUpdateUserStatus(int operation, String adminName, List<Integer> userIds) {
        // 遍历用户ID列表，对每个用户执行状态更新
        for (int userId : userIds) {
            boolean success = updateUserStatus(operation, adminName, userId);
            if (!success) {
                return false; // 如果有任意一个用户更新失败，返回false
            }
        }
        return true; // 所有用户更新成功
    }

    //记录管理员操作日志
    public static void recordOperationLog(String managerName,String operation,String userName){
        managerName=managerName.trim();
        userName=userName.trim();
        operation=operation.trim();
        // 获取当前时间,年月日时分秒
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        //  记录管理员操作日志
        int type = 2;
        Object[] objects = {managerName,userName,operation,type,formattedDateTime};
        try {
            DatabaseOperations.executeUpdate(DatabaseSQl.recordOperationLogSql(),objects);
        }catch (Exception e){
            e.printStackTrace();
        }
        // 通知用户的操作
        type=0;
        Object[] objects1 = {managerName,userName,operation,type,formattedDateTime};
        try {
            DatabaseOperations.executeUpdate(DatabaseSQl.recordOperationLogSql(),objects1);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static List<Message> getOperationLogs(){
        List<Message> messages = new ArrayList<>();
        int type  = 2;
        try {
            ResultSet resultSet = DatabaseOperations.executeQuery(DatabaseSQl.selectOperationLogSql(),new Object[]{type});
            while (resultSet.next()){
                Message message = new Message(
                        resultSet.getString("sendMessage"),
                        resultSet.getString("receiveMessage"),
                        resultSet.getString("content"),
                        resultSet.getInt("type"),
                        resultSet.getString("time")
                );
                messages.add(message);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return messages;

    }




}
